<?php

namespace App\Http\Controllers\Api;

use App\ActivityGroup;
use App\ActivityGroupAdd;
use App\ActivityGroupPrice;
use App\ChargeAvailable;
use App\Chongzhi;
use App\Classify;
use App\Comment;
use App\CommentImg;
use App\CommentLike;
use App\DiscountSalesRule;
use App\DiscountXGoods;
use App\Express;
use App\Files;
use App\Goods;
use App\GoodsBanner;
use App\GoodsImg;
use App\GoodSpu;
use App\GoodsServiceLabel;
use App\GoodsSnapshot;
use App\GoodsSpu;
use App\GoodsSpuShop;
use App\Http\Services\FileManager;
use App\Http\Services\UserManager;
use App\Http\Services\Wechat\WechatLogin;
use App\Images;
use App\OrderItem;
use App\Orders;
use App\ShopCart;
use App\Shops;
use App\ShowGoods;
use App\User;
use App\UserInfo;
use Faker\Provider\File;
use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;
use Intervention\Image\Facades\Image;

class GoodsController extends Controller
{
    /**
     * 获取商品列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGoodsList(Request $request){
        $limit      = !is_null($request->get('limit')) ? $request->get('limit') : 20;
        $page       = !is_null($request->get('page')) ? $request->get('page') : 1;
        $classifyId = !is_null($request->get('classify_id')) ? $request->get('classify_id') : 0;
        $goodsName  = $request->get('goods_name');

        /** @var User $user */
        $user = UserManager::isLogin($request);
//        if(!$user)
//            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);
        $user_id=$user ? $user->id : 0;

        /** @var Goods $Goods*/
        $allGoods = DB::table('goods')->whereIsShop(1)->whereNull('deleted_at');

        if($classifyId != 0 && $classifyId != '') {
            $allGoods->whereClassifyId($classifyId);
        }

        if(!is_null($goodsName) && $goodsName != ''){
            $allGoods = $allGoods->where('name','like','%'.trim($goodsName).'%');
            //TODO 记录搜索
            OtherController::addSearchRecord($goodsName,$user_id,$request->ip());
        }

        $allGoods = $allGoods->whereType('common')->orderBy('sale_count','desc')->orderBy('sort','asc')->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();

        if(count($allGoods) > 0){
            foreach($allGoods as $Goods){
                $Goods->thumb_Url = FileManager::getImgUrl($Goods->thumb_id);

                /** @var GoodsSpu $goodSpu */
                $goodSpuList = GoodsSpu::whereGoodsId($Goods->id)->whereStatus(1)->orderBy('sort','asc')->get();
                $goodsPriceArr = array();
                if(count($goodSpuList) > 0){
                    foreach($goodSpuList as $goodSpu){
                        array_push($goodsPriceArr,$goodSpu->price);
                    }
                    //商品最低价
                    $goodsGroupPrice = min($goodsPriceArr);
                    $Goods->s_price = $goodsGroupPrice;
                }





                /** @var GoodsSpu $goodsSpuDefault */
                $goodsSpuDefault = GoodsSpu::whereGoodsId($Goods->id)->whereStatus(1)->orderBy('sort','asc')->first();
                if($goodsSpuDefault){
                    $Goods->default_goods_spu_id = $goodsSpuDefault->id;
                }else{
                    $Goods->default_goods_spu_id = 0;
                }

                if($user){
                    /** @var ShopCart $shopCart */
                    $shopCarts = ShopCart::whereUserId($user->id)->whereGoodsId($Goods->id)->sum('num');
                }else{
                    $shopCarts = 0;
                }

                $Goods->total_goods_num = $shopCarts;
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $allGoods]);
    }

    public function getSectionGoodsList(Request $request){
        $sections = Classify::whereType("section")->whereHomeShow(1)->orderBy("updated_at","desc")->get();
        if(count($sections) > 0){
            foreach ($sections as $section){
                $section->advert_img_url = FileManager::getImgUrl($section->advert_img_id);

                $classifyIds = Classify::whereClassifyId($section->id)->pluck("id")->toArray();
                $goods = Goods::whereIn("classify_id",$classifyIds)->orderBy("created_at","desc")->limit(10)->get();
                if(count($goods) > 0){
                    foreach ($goods as $good){
                        $good->thumb_img_url = FileManager::getImgUrl($good->thumb_id);
                    }
                }
                $section->goods_list = $goods;
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $sections]);
    }

    public function getSectionClassifyList(Request $request){
        $sectionId = $request->get("section_id");

        $sections = Classify::whereType("section")->orderBy("sort","asc")->get()->toArray();
        if(count($sections) > 0) {
           if(is_null($sectionId) || $sectionId == 0){
               $classifys = Classify::whereClassifyId($sections[0]["id"])->wherePid(0)->get();
               $sectionId = $sections[0]["id"];
           }else{
               $classifys = Classify::whereClassifyId($sectionId)->wherePid(0)->get();
           }
        }else{
            $classifys = [];
            $sectionId = 0;
        }

        if(count($classifys) > 0){
            foreach ($classifys as $classify){
                $classify->img_url = FileManager::getImgUrl($classify->img_id);
            }
        }

        $result = [
            "sections"=>$sections,
            "classifys"=>$classifys,
            "section_id"=>$sectionId
        ];

        return response()->json(['level' => 'success','message' => '获取成功','data' => $result]);
    }

    public function getSectionClassifyTwoList(Request $request){
        $sectionId     = $request->get("section_id");
        $classifyId    = $request->get("classify_id");

        $classifys = Classify::whereType("goods")->get();
//        $sections = Classify::whereType("section")->orderBy("sort","asc")->get()->toArray();
//        if(count($sections) > 0) {
//            if(is_null($sectionId) || $sectionId == 0){
//                $classifys = Classify::whereClassifyId($sections[0]["id"])->wherePid(0)->get()->toArray();
//                $sectionId = $sections[0]["id"];
//            }else{
//                $classifys = Classify::whereClassifyId($sectionId)->wherePid(0)->get()->toArray();
//            }
//
//            if(count($classifys) > 0){
//                if(is_null($classifyId) || $classifyId == 0){
//                    $childClassifys = Classify::wherePid($classifys[0]["id"])->get()->toArray();
//                    $classifyId = $classifys[0]["id"];
//                }else{
//                    $childClassifys = Classify::wherePid($classifyId)->get()->toArray();
//                }
//            }else{
//                $childClassifys = [];
//            }
//
//        }else{
//            $classifys      = [];
//            $childClassifys = [];
//            $sectionId = 0;
//        }

//        if(count($sections) > 0){
//            foreach ($sections as $key=>$section){
//                $sections[$key]["img_url"] = FileManager::getImgUrl($section["img_id"]);
//            }
//        }

        $result = [
            "sections"        => [],
            "classifys"       => $classifys,
            "child_classifys" => [],
            "section_id"      => $sectionId,
            "classify_id"     => $classifyId,
        ];

        return response()->json(['level' => 'success','message' => '获取成功','data' => $result]);
    }

    public function getGoodsListByClassifyId(Request $request){
        $user       = UserManager::isLogin($request);
        $limit      = !is_null($request->get('limit')) ? $request->get('limit') : 100;
        $page       = !is_null($request->get('page')) ? $request->get('page') : 1;
        $classifyId    = !is_null($request->get('classify_id')) ? $request->get('classify_id') : 0;
        $classifyTwoId = !is_null($request->get('classify_two_id')) ? $request->get('classify_two_id') : 0;

        /** @var Goods $Goods*/
        $allGoods = DB::table('goods')->whereIsShop(1)->whereNull('deleted_at');

        if($classifyTwoId != 0){
            $allGoods = $allGoods->whereClassifyTwoId($classifyTwoId);
        }else{
            $allGoods = $allGoods->whereClassifyId($classifyId);
        }

        $total = $allGoods->whereType('common')->count();

        $allGoods = $allGoods->whereType('common')->orderBy('sale_count','desc')->orderBy('sort','asc')->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();

        $page_info=[
            'limit'=>$limit,
            'page'=>$page,
            'total'=>$total
        ];

        if(count($allGoods) > 0){
            foreach($allGoods as $Goods){
                $Goods->thumb_Url = FileManager::getImgUrl($Goods->thumb_id);

                /** @var GoodsSpu $goodSpu */
                $goodSpuList = GoodsSpu::whereGoodsId($Goods->id)->whereStatus(1)->orderBy('sort','asc')->get();
                $goodsPriceArr = array();
                if(count($goodSpuList) > 0){
                    foreach($goodSpuList as $goodSpu){
                        array_push($goodsPriceArr,$goodSpu->price);
                    }
                    //商品最低价
                    $goodsGroupPrice = min($goodsPriceArr);

                    $Goods->s_price = $goodsGroupPrice;
                }



                /** @var GoodsSpu $goodsSpuDefault */
                $goodsSpuDefault = GoodsSpu::whereGoodsId($Goods->id)->whereStatus(1)->orderBy('sort','asc')->first();
                if($goodsSpuDefault){
                    $Goods->default_goods_spu_id = $goodsSpuDefault->id;
                }else{
                    $Goods->default_goods_spu_id = 0;
                }

                if($user){
                    /** @var ShopCart $shopCart */
                    $shopCarts = ShopCart::whereUserId($user->id)->whereGoodsId($Goods->id)->sum('num');
                }else{
                    $shopCarts = 0;
                }

                $Goods->total_goods_num = $shopCarts;
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $allGoods,"page_info"=>$page_info]);
    }

    /**
     * 获取推荐商品列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getRecommendGoodsList(Request $request){
        $user = UserManager::isLogin($request);
        $limit      = !is_null($request->get('limit')) ? $request->get('limit') : 20;
        $page       = !is_null($request->get('page')) ? $request->get('page') : 1;

        /** @var Goods $Goods*/
        $allGoods = DB::table('goods')->whereIsShop(1)->whereNull('deleted_at');

        $allGoods = $allGoods->whereIsRecommend(1)->whereType('common')->orderBy('sale_count','desc')->orderBy('sort','asc')->orderBy('created_at','desc')->offset($limit * ($page - 1))->limit($limit)->get();

        $total = DB::table('goods')->whereIsShop(1)->whereNull('deleted_at')->whereIsRecommend(1)->whereType('common')->count();
        $page_info=[
            'limit'=>$limit,
            'page'=>$page,
            'total'=>$total
        ];

        if(count($allGoods) > 0){
            foreach($allGoods as $Goods){
                $Goods->thumb_Url = FileManager::getImgUrl($Goods->thumb_id);

                /** @var GoodsSpu $goodSpu */
                $goodSpuList = GoodsSpu::whereGoodsId($Goods->id)->whereStatus(1)->orderBy('sort','asc')->get();
                $goodsPriceArr = array();
                if(count($goodSpuList) > 0){
                    foreach($goodSpuList as $goodSpu){
                        array_push($goodsPriceArr,$goodSpu->price);
                    }
                    //商品最低价
                    $goodsGroupPrice = min($goodsPriceArr);

                    $Goods->s_price = $goodsGroupPrice;
                }



                /** @var GoodsSpu $goodsSpuDefault */
                $goodsSpuDefault = GoodsSpu::whereGoodsId($Goods->id)->whereStatus(1)->orderBy('sort','asc')->first();
                if($goodsSpuDefault){
                    $Goods->default_goods_spu_id = $goodsSpuDefault->id;
                }else{
                    $Goods->default_goods_spu_id = 0;
                }

                if($user){
                    /** @var ShopCart $shopCart */
                    $shopCarts = ShopCart::whereUserId($user->id)->whereGoodsId($Goods->id)->sum('num');
                }else{
                    $shopCarts = 0;
                }

                $Goods->total_goods_num = $shopCarts;
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $allGoods,"page_info"=>$page_info]);
    }

    /**
     * 获取商品分类（含二级）
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGoodsClassify(Request $request){
        $type = !is_null($request->get('type')) && $request->get('type') != '' ? $request->get('type') : 'goods';

        if($type == 'goods'){
            /** @var Classify $classify */
            $classifies = Classify::wherePid(0)->whereType('goods')->orderBy('sort','asc')->orderBy('created_at','desc')->get();
            if(count($classifies) > 0){
                foreach($classifies as $classify){
                    $SecondaryClassify = Classify::wherePid($classify->id)->orderBy('sort','asc')->orderBy('created_at','desc')->get();
                    $classify->secondary_classify = $SecondaryClassify;

                    $classify->img_url = FileManager::getImgUrl($classify->img_id);
                }
            }
        }elseif($type == 'section'){
            /** @var Classify $classify */
            $classifies = Classify::whereType('section')->orderBy('sort','asc')->orderBy('created_at','asc')->get();
            if(count($classifies) > 0){
                foreach($classifies as $classify){
                    $classify->img_id = FileManager::getImgUrl($classify->img_id);
                }
            }
        }else{
            $classifies = [];
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $classifies]);
    }

    /**
     * 获取商品详情
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getGoodsDetails(Request $request){
        $user = UserManager::isLogin($request);
        $user_id=$user ? $user->id :0;
        $goodsId         = !is_null($request->get('goods_id')) ? $request->get('goods_id') : 0;
        $activityGroupId = !is_null($request->get('activity_group_id')) ? $request->get('activity_group_id') : 0;

        /** @var Goods $goodsDetails */
        $goodsDetails = Goods::whereId($goodsId)->whereIsShop(1)->first();
        if($goodsDetails){
            $goodsDetails->thumb_url = FileManager::getImgUrl($goodsDetails->thumb_id);

            $goodsDetails->detail = str_replace("/uploads/ueditor/php/upload/image",env('HOST_URL')."/uploads/ueditor/php/upload/image",$goodsDetails->detail);

            /** @var GoodsSpu $goodSpu */
            $goodSpuList = GoodsSpu::whereGoodsId($goodsDetails->id)->whereStatus(1)->orderBy('sort','asc')->get();
            $goodsPriceArr = array();
            if(count($goodSpuList) > 0){
                foreach($goodSpuList as $goodSpu){
                    $goodSpu->img_url=FileManager::getImgUrl($goodSpu->img_id);
                    array_push($goodsPriceArr,$goodSpu->price);
                }
                //商品最低价
                $goodsGroupPrice = min($goodsPriceArr);

                $goodsDetails->s_price = $goodsGroupPrice;
            }

            /** @var GoodsBanner $goodsBanner */
            $goodsBanners = GoodsBanner::whereGoodsId($goodsDetails->id)->orderBy('sort','asc')->orderBy('created_at','desc')->get();
            $goodsBannerUrls = array();
            if(count($goodsBanners) > 0){
                foreach($goodsBanners as $goodsBanner){
                    $goodsBannerUrl = FileManager::getImgUrl($goodsBanner->img_id);
                    array_push($goodsBannerUrls,$goodsBannerUrl);
                }
            }

            $goodsDetails->goods_banner = $goodsBannerUrls;

            /** @var GoodsServiceLabel $goodsServiceLabel */
            $goodsServiceLabelList = GoodsServiceLabel::orderBy('sort','asc')->orderBy('created_at','desc')->get();
            $goodsDiscountList = DiscountXGoods::whereGoodsId($goodsId)->get();
            $goodsServiceLabelArr = array();
            $goodsDiscountLabelArr = array();
            if(count($goodsServiceLabelList) > 0){
                foreach($goodsServiceLabelList as $goodsServiceLabel){
                    array_push($goodsServiceLabelArr,$goodsServiceLabel->name);
                }
            }

            if (count($goodsDiscountList) > 0){
                $isVip=ChargeAvailable::whereUserId($user_id)->first();

                /** @var DiscountXGoods $item */
                foreach($goodsDiscountList as $item){
                    $temp=DiscountSalesRule::whereId($item->discount_sales_rule_id)->whereStatus(1)->first();
                    if ($temp){
                        if ($temp->range=='vip' && $isVip){
                            if (!is_null($temp->start_time) && !is_null($temp->end_time)) {
                                if (strtotime($temp->start_time) <= time() && time() < strtotime($temp->end_time))
                                    array_push($goodsDiscountLabelArr, $temp);
                            } else {
                                array_push($goodsDiscountLabelArr,$temp);
                            }
                        }  elseif ($temp->range=='all'){
                            if (!is_null($temp->start_time) && !is_null($temp->end_time)) {
                                if (strtotime($temp->start_time) <= time() && time() < strtotime($temp->end_time))
                                    array_push($goodsDiscountLabelArr, $temp);
                            } else {
                                array_push($goodsDiscountLabelArr,$temp);
                            }
                        }

                    }

                }

            }

            $goodsDetails->goods_service_label_list = $goodsServiceLabelArr;

            if ($goodsDetails->is_free_shipping){
                $goodsDetails->express_fee=0;
            } else {
                $express=Express::whereIsDefault(1)->first();
                $goodsDetails->express_fee=$express ? $express->fee :0;
            }

            $goodsDetails->goods_spu_info   = $goodSpuList;
            $goodsDetails->discount_info    = $goodsDiscountLabelArr;
        }else{
            return response()->json(['level' => 'error','message' => '该商品已下架']);
        }

        return response()->json(['level' => 'success','message' => '获取商品详情','data' => $goodsDetails]);
    }

    /**
     * 添加购物车接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function addShopCart(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $goodsId  = !is_null($request->get('goods_id')) ? $request->get('goods_id') : 0;
        $num      = !is_null($request->get('num')) ? $request->get('num') : 1;
        $goodsSpu = !is_null($request->get('goods_spu_id')) ? $request->get('goods_spu_id') : 0;

        /** @var Goods $thisGoods */
        $thisGoods = Goods::whereId($goodsId)->whereIsShop(1)->first();
        if(!$thisGoods)
            return response()->json(['level' => 'error','message' => '该商品已下架']);

        if(is_null($goodsSpu) || $goodsSpu == 0)
            return response()->json(['level' => 'error','message' => '请选择规格']);

        /** @var GoodsSpu $thisGoodsSpu */
        $thisGoodsSpu = GoodsSpu::whereId($goodsSpu)->whereGoodsId($thisGoods->id)->whereStatus(1)->first();
        if(!$thisGoodsSpu){
            return response()->json(['level' => 'error','message' => '该商品规格不存在']);
        }

        /** @var ShopCart $newShopCart */
        $newShopCart = ShopCart::whereUserId($user->id)->whereGoodsId($thisGoods->id)->whereGoodsSpuId($thisGoodsSpu->id)->first();
        if($newShopCart){
            if($num == -1 && $num != ''){
                $resultNum = (int)$newShopCart->num + (int)$num;
                $newShopCart->num          = $resultNum;
                $newShopCart->amount_money = (float)$newShopCart->unit_price * $resultNum;
                $newShopCart->save();

                if($newShopCart->num < 1){
                    $newShopCart->delete();
                }
            }else if($num == 1 && $num != ''){
                if($thisGoodsSpu->stock < $num || $thisGoodsSpu->stock == 0)
                    return response()->json(['level' => 'error','message' => '商品库存不足']);

                $resultNum = (int)$newShopCart->num + (int)$num;
                $newShopCart->num          = $resultNum;
                $newShopCart->amount_money = (float)$newShopCart->unit_price * $resultNum;
                $newShopCart->save();
            }
        }else{
            if($num == -1 || $num == '')
                return response()->json(['level' => 'error','message' => '操作错误']);

            if($thisGoodsSpu->stock < $num || $thisGoodsSpu->stock == 0)
                return response()->json(['level' => 'error','message' => '商品库存不足']);

            $newShopCart = new ShopCart();
            $newShopCart->user_id      = $user->id;
            $newShopCart->goods_id     = $thisGoods->id;
            $newShopCart->goods_spu_id  = $thisGoodsSpu->id;
            $newShopCart->unit_price   = $thisGoodsSpu->price;
            $newShopCart->num          = $num;
            $newShopCart->amount_money = (float)$newShopCart->unit_price * (int)$newShopCart->num;
            $newShopCart->save();
        }

        /** @var ShopCart $shopCart */
        $shopCarts = ShopCart::whereUserId($user->id)->sum('num');

        return response()->json(['level' => 'success','message' => '添加购物车成功','data' => $newShopCart,'total_goods_num' => $shopCarts]);
    }

    /**
     * 获取购物车列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getShopCart(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $limit    = !is_null($request->get('limit')) ? $request->get('limit') : 20;
        $page     = !is_null($request->get('page')) ? $request->get('page') : 1;

        /** @var ShopCart $shopCart */
        $shopCarts = ShopCart::whereUserId($user->id)->offset($limit * ($page - 1))->limit($limit)->get();
        $isDelete = 0;
        if(count($shopCarts) > 0){
            foreach($shopCarts as $shopCart){
                /** @var Goods $thisGoods */
                $thisGoods = Goods::whereId($shopCart->goods_id)->whereIsShop(1)->first();
                if($thisGoods){
                    $thisGoods->thumb_Url = FileManager::getImgUrl($thisGoods->thumb_id);

                    $thisGoods->s_price   = $shopCart->unit_price;
                }else{
                    $shopCart->delete();
                    $isDelete += 1;
                }

                if($shopCart){
                    $thisGoodsSpu = GoodsSpu::whereGoodsId($thisGoods->id)->whereId($shopCart->goods_spu_id)->whereStatus(1)->first();
                    if(!$thisGoodsSpu){
                        $shopCart->delete();
                        $isDelete += 1;
                    }

                    if($shopCart){
                        $thisGoods->goods_spu_info = $thisGoodsSpu;
                        $shopCart->goods_info      = $thisGoods;
                    }
                }
            }

        }

        if($isDelete != 0){
            return response()->json(['level' => 'error','message' => '您的购物车中已有'.$isDelete.'件商品被下架']);
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $shopCarts]);
    }

    /**
     * 删除购物车
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function deleteShopCart(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $shopCartIds = $request->get('shop_cart_ids');

        if(is_array($shopCartIds)){
            foreach($shopCartIds as $shopCartId){
                $thisShopCart = ShopCart::whereId($shopCartId)->whereUserId($user->id)->first();
                if($thisShopCart){
                    $thisShopCart->delete();
                }
            }
        }else{
            return response()->json(['level' => 'error','message' => '数据格式错误']);
        }

        return response()->json(['level' => 'success','message' => '删除成功']);
    }

    public function generateShareQrCode(Request $request){
//        /** @var User $user */
//        $user = UserManager::isLogin($request);
//        if(!$user)
//            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $goodsId = !is_null($request->get('goods_id')) ? $request->get('goods_id') : 0;

//        /** @var UserInfo $userInfo */
//        $userInfo = UserInfo::whereUserId($user->id)->first();
//        if(!$userInfo)
//            return response()->json(['level' => 'error','message' => '用户信息不存在']);

        /** @var Goods $thisGoods */
        $thisGoods = Goods::whereId($goodsId)->whereType('common')->first();
        if(!$thisGoods)
            return response()->json(['level' => 'error','message' => '拼团商品信息不存在']);

        //背景图片
        $backgroundImgInfo = Image::make(url('images/bj.png'));

        //获取拼团商品图片
        if($thisGoods->thumb_id != 0){
            /** @var Images $thisImage */
            $thisImage = Images::whereId($thisGoods->thumb_id)->first();
            if($thisImage){
                /** @var Files $thisFile */
                $thisFile = Files::whereId($thisImage->file_id)->first();
                if($thisFile){
                    $goodsThumbImgContent = $thisFile->getContent();
                }else{
                    $goodsThumbImgContent = url('images/default_img.png');
                }
            }else{
                $goodsThumbImgContent = url('images/default_img.png');
            }
        }else{
            $goodsThumbImgContent = url('images/default_img.png');
        }

        //拼团商品图
        $goodsThumbImgINfo = Image::make($goodsThumbImgContent);

        //吊证拼团商品图大小
        $goodsThumbImgINfo->resize(642,642);

        //吊证拼团商品图在背景图上的位置
        $backgroundImgInfo->insert($goodsThumbImgINfo,'top-left',54,108);

        //商品名称
        //商品名称的长度
        $goodsCount = mb_strlen($thisGoods->name);
        if($goodsCount && $goodsCount > 13){
            //截取前四个字
            $goodsNameOne = mb_substr($thisGoods->name,0,13,'utf-8');
            //调整商品名称在图片上的位置
            $backgroundImgInfo->text('【'.$goodsNameOne, 65, 780, function($font) {
                $font->file(base_path()."/public/front/simsun.ttc");
//            $font->file(1);
                $font->size(30);
                $font->color('#000000');//5a5a5a
                $font->align('left');
                $font->valign('top');
                $font->angle(0);
            });

            //调整商品名称在图片上的位置
            $backgroundImgInfo->text('【'.$goodsNameOne, 65, 780, function($font) {
                $font->file(base_path()."/public/front/simsun.ttc");
//            $font->file(1);
                $font->size(30);
                $font->color('#000000');//5a5a5a
                $font->align('left');
                $font->valign('top');
                $font->angle(0);
            });

            //调整商品名称在图片上的位置
            $backgroundImgInfo->text('【'.$goodsNameOne, 65, 781, function($font) {
                $font->file(base_path()."/public/front/simsun.ttc");
//            $font->file(1);
                $font->size(30);
                $font->color('#000000');//5a5a5a
                $font->align('left');
                $font->valign('top');
                $font->angle(0);
            });

            //调整商品名称在图片上的位置
            $backgroundImgInfo->text('【'.$goodsNameOne, 65, 781, function($font) {
                $font->file(base_path()."/public/front/simsun.ttc");
//            $font->file(1);
                $font->size(30);
                $font->color('#000000');//5a5a5a
                $font->align('left');
                $font->valign('top');
                $font->angle(0);
            });

            if($goodsCount > 26){
                //截取后面的数字
                $goodsNameTwo = mb_substr($thisGoods->name,13,13,'utf-8');

                //调整商品名称在图片上的位置
                $backgroundImgInfo->text($goodsNameTwo, 65, 815, function($font) {
                    $font->file(base_path()."/public/front/simsun.ttc");
//            $font->file(1);
                    $font->size(30);
                    $font->color('#000000');//5a5a5a
                    $font->align('left');
                    $font->valign('top');
                    $font->angle(0);
                });

                //调整商品名称在图片上的位置
                $backgroundImgInfo->text($goodsNameTwo, 65, 815, function($font) {
                    $font->file(base_path()."/public/front/simsun.ttc");
//            $font->file(1);
                    $font->size(30);
                    $font->color('#000000');//5a5a5a
                    $font->align('left');
                    $font->valign('top');
                    $font->angle(0);
                });

                //调整商品名称在图片上的位置
                $backgroundImgInfo->text($goodsNameTwo, 65, 816, function($font) {
                    $font->file(base_path()."/public/front/simsun.ttc");
//            $font->file(1);
                    $font->size(30);
                    $font->color('#000000');//5a5a5a
                    $font->align('left');
                    $font->valign('top');
                    $font->angle(0);
                });

                //调整商品名称在图片上的位置
                $backgroundImgInfo->text($goodsNameTwo, 65, 816, function($font) {
                    $font->file(base_path()."/public/front/simsun.ttc");
//            $font->file(1);
                    $font->size(30);
                    $font->color('#000000');//5a5a5a
                    $font->align('left');
                    $font->valign('top');
                    $font->angle(0);
                });

                //截取后面的数字
                $goodsNameThree = mb_substr($thisGoods->name,26,null,'utf-8');

                $goodsNameThree = mb_strimwidth($goodsNameThree,0,24,'...','utf-8');
                //调整商品名称在图片上的位置
                $backgroundImgInfo->text($goodsNameThree.'】', 65, 850, function($font) {
                    $font->file(base_path()."/public/front/simsun.ttc");
//            $font->file(1);
                    $font->size(30);
                    $font->color('#000000');//5a5a5a
                    $font->align('left');
                    $font->valign('top');
                    $font->angle(0);
                });

                //调整商品名称在图片上的位置
                $backgroundImgInfo->text($goodsNameThree.'】', 65, 850, function($font) {
                    $font->file(base_path()."/public/front/simsun.ttc");
//            $font->file(1);
                    $font->size(30);
                    $font->color('#000000');//5a5a5a
                    $font->align('left');
                    $font->valign('top');
                    $font->angle(0);
                });

                //调整商品名称在图片上的位置
                $backgroundImgInfo->text($goodsNameThree.'】', 65, 851, function($font) {
                    $font->file(base_path()."/public/front/simsun.ttc");
//            $font->file(1);
                    $font->size(30);
                    $font->color('#000000');//5a5a5a
                    $font->align('left');
                    $font->valign('top');
                    $font->angle(0);
                });

                //调整商品名称在图片上的位置
                $backgroundImgInfo->text($goodsNameThree.'】', 65, 851, function($font) {
                    $font->file(base_path()."/public/front/simsun.ttc");
//            $font->file(1);
                    $font->size(30);
                    $font->color('#000000');//5a5a5a
                    $font->align('left');
                    $font->valign('top');
                    $font->angle(0);
                });
            }else{
                //截取后面的数字
                $goodsNameTwo = mb_substr($thisGoods->name,13,null,'utf-8');

                $goodsNameTwo = mb_strimwidth($goodsNameTwo,0,24,'...','utf-8');
                //调整商品名称在图片上的位置
                $backgroundImgInfo->text($goodsNameTwo.'】', 65, 815, function($font) {
                    $font->file(base_path()."/public/front/simsun.ttc");
//            $font->file(1);
                    $font->size(30);
                    $font->color('#000000');//5a5a5a
                    $font->align('left');
                    $font->valign('top');
                    $font->angle(0);
                });

                //调整商品名称在图片上的位置
                $backgroundImgInfo->text($goodsNameTwo.'】', 65, 815, function($font) {
                    $font->file(base_path()."/public/front/simsun.ttc");
//            $font->file(1);
                    $font->size(30);
                    $font->color('#000000');//5a5a5a
                    $font->align('left');
                    $font->valign('top');
                    $font->angle(0);
                });

                //调整商品名称在图片上的位置
                $backgroundImgInfo->text($goodsNameTwo.'】', 65, 816, function($font) {
                    $font->file(base_path()."/public/front/simsun.ttc");
//            $font->file(1);
                    $font->size(30);
                    $font->color('#000000');//5a5a5a
                    $font->align('left');
                    $font->valign('top');
                    $font->angle(0);
                });

                //调整商品名称在图片上的位置
                $backgroundImgInfo->text($goodsNameTwo.'】', 65, 816, function($font) {
                    $font->file(base_path()."/public/front/simsun.ttc");
//            $font->file(1);
                    $font->size(30);
                    $font->color('#000000');//5a5a5a
                    $font->align('left');
                    $font->valign('top');
                    $font->angle(0);
                });
            }

        }else{
            //调整商品名称在图片上的位置
            $backgroundImgInfo->text('【'.$thisGoods->name.'】', 65, 780, function($font) {
                $font->file(base_path()."/public/front/simsun.ttc");
//            $font->file(1);
                $font->size(30);
                $font->color('#000000');//5a5a5a
                $font->align('left');
                $font->valign('top');
                $font->angle(0);
            });

            //调整商品名称在图片上的位置
            $backgroundImgInfo->text('【'.$thisGoods->name.'】', 65, 780, function($font) {
                $font->file(base_path()."/public/front/simsun.ttc");
//            $font->file(1);
                $font->size(30);
                $font->color('#000000');//5a5a5a
                $font->align('left');
                $font->valign('top');
                $font->angle(0);
            });

            //调整商品名称在图片上的位置
            $backgroundImgInfo->text('【'.$thisGoods->name.'】', 65, 781, function($font) {
                $font->file(base_path()."/public/front/simsun.ttc");
//            $font->file(1);
                $font->size(30);
                $font->color('#000000');//5a5a5a
                $font->align('left');
                $font->valign('top');
                $font->angle(0);
            });

            //调整商品名称在图片上的位置
            $backgroundImgInfo->text('【'.$thisGoods->name.'】', 65, 781, function($font) {
                $font->file(base_path()."/public/front/simsun.ttc");
//            $font->file(1);
                $font->size(30);
                $font->color('#000000');//5a5a5a
                $font->align('left');
                $font->valign('top');
                $font->angle(0);
            });

        }

        $goodSpuPrice = GoodsSpu::whereGoodsId($thisGoods->id)->whereStatus(1)->pluck('price');
        //单独购买最低价
        $GoodsPriceMin = min($goodSpuPrice->toArray());
        $GoodsPriceMax = max($goodSpuPrice->toArray());

        if($GoodsPriceMin == $GoodsPriceMax){
            $goodsMoney = '￥' . $GoodsPriceMin;
        }else{
            $goodsMoney = '￥' . $GoodsPriceMin . ' ～ ' . '￥' . $GoodsPriceMax;
        }

        //调整单独购买最低价在图片上的位置
        $backgroundImgInfo->text($goodsMoney, 65, 940, function($font) {
            $font->file(base_path()."/public/front/simsun.ttf");
//            $font->file(1);
            $font->size(30);
            $font->color('#E22018');//5a5a5a
            $font->align('left');
            $font->valign('top');
            $font->angle(0);
        });
        //调整单独购买最低价在图片上的位置
        $backgroundImgInfo->text($goodsMoney, 65, 940, function($font) {
            $font->file(base_path()."/public/front/simsun.ttf");
//            $font->file(1);
            $font->size(30);
            $font->color('#E22018');//5a5a5a
            $font->align('left');
            $font->valign('top');
            $font->angle(0);
        });
        //调整单独购买最低价在图片上的位置
        $backgroundImgInfo->text($goodsMoney, 65, 941, function($font) {
            $font->file(base_path()."/public/front/simsun.ttf");
//            $font->file(1);
            $font->size(30);
            $font->color('#E22018');//5a5a5a
            $font->align('left');
            $font->valign('top');
            $font->angle(0);
        });
        //调整单独购买最低价在图片上的位置
        $backgroundImgInfo->text($goodsMoney, 65, 941, function($font) {
            $font->file(base_path()."/public/front/simsun.ttf");
//            $font->file(1);
            $font->size(30);
            $font->color('#E22018');//5a5a5a
            $font->align('left');
            $font->valign('top');
            $font->angle(0);
        });


        $scene = "id=".$thisGoods->id;
        $path  = 'pages/goodsDetail/main?'.$scene;      //梓杰给

        //生成微信小程序的二维码图片
        $wxAppQrCodeContent = WechatLogin::getWxQrcodeByToken($path);
        if($wxAppQrCodeContent){
            //获取二维码图片
            $wxAppQrCodeImgINfo = Image::make($wxAppQrCodeContent)->resize(125,125);
            //调整二维码图片在图片上的位置
            $backgroundImgInfo->insert($wxAppQrCodeImgINfo,'top-left',560,810);

        }else{
            return response()->json(['level' => 'error','message' => '二维码生成失败,请联系客服']);
        }

        //长按识别二维码
        $activityTimeInfo = "长按小程序码购买";

        //调整长按识别二维码在图片上的位置
        $backgroundImgInfo->text($activityTimeInfo,543,950, function($font) {
            $font->file(base_path()."/public/front/simsun.ttf");
//            $font->file(1);
            $font->size(20);
            $font->color('#808080');//5a5a5a
            $font->align('left');
            $font->valign('top');
            $font->angle(0);
        });

        //输出图片
        $response = response()->make($backgroundImgInfo->encode('png'));
        $response->header('Content-Type', 'image/png');

        return $response;
    }

    /**
     * 用户评论接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function userComment(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        /* if(is_null($user->phone) || $user->phone == '')
           return response()->json(['level' => 'error','message' => '请绑定手机号','data' => 'no_binding']); */
        $commentList   = $request->get('comment_list');

        if(!is_array($commentList))
            return response()->json(['level' => 'error','message' => '数据类型错误']);

        if(count($commentList) > 0){
            foreach($commentList as $comment){
                /** @var Orders $thisOrders */
                $thisOrders = Orders::whereOrderNum($comment['order_num'])->whereUserId($user->id)->first();
                if(!$thisOrders)
                    return response()->json(['level' => 'error','message' => '该订单不存在']);

                /** @var Goods $goods */
                $goods = Goods::whereId($comment['goods_id'])->whereIsShop(1)->first();
                if(!$goods)
                    return response()->json(['level' => 'error','message' => '商品已下架']);

                if($goods->type == 'common'){
                    /** @var GoodsSpu $thisGoodsSpu */
                    $thisGoodsSpu = GoodsSpu::whereId($comment['goods_spu'])->first();
                    if(!$thisGoodsSpu)
                        return response()->json(['level' => 'error','message' => '商品属性不存在']);

                    /** @var OrderItem $orderItems */
                    $orderItems = OrderItem::whereOrderId($thisOrders->id)->whereGoodsId($goods->id)->whereGoodsSpuId($thisGoodsSpu->id)->first();
                    if(!$orderItems)
                        return response()->json(['level' => 'error','message' => '订单错误!']);

                    $isComment = Comment::whereUserId($user->id)->whereOrderNum($thisOrders->order_num)->whereGoodsId($goods->id)->whereGoodsSpuId($thisGoodsSpu->id)->first();
                    if(!$isComment){
                        if(!is_null($comment['content']) && trim($comment['content']) != ''){
                            $newComment = new Comment();
                            $newComment->user_id                   = $user->id;
                            $newComment->order_num                 = $thisOrders->order_num;
                            $newComment->goods_id                  = $goods->id;
                            $newComment->goods_spu_id              = $thisGoodsSpu->id;
                            $newComment->content                   = $comment['content'];
                            $newComment->save();
                        }else{
                            $newComment = null;
                        }

                        if(is_array($comment['img_ids']) && count($comment['img_ids']) >0){
                            if(!$newComment){
                                $newComment = new Comment();
                                $newComment->user_id                   = $user->id;
                                $newComment->order_num                 = $thisOrders->order_num;
                                $newComment->goods_id                  = $goods->id;
                                $newComment->goods_spu_id              = $thisGoodsSpu->id;
                                $newComment->save();
                            }

                            foreach($comment['img_ids'] as $imgId){
                                $newCommentImg = new CommentImg();
                                $newCommentImg->comment_id = $newComment->id;
                                $newCommentImg->img_id     = $imgId;
                                $newCommentImg->save();
                            }
                        }

                        if($newComment){
                            $orderItems->status = 1;
                            $orderItems->save();
                        }
                    }

                }else{
                    return response()->json(['level' => 'error','message' => '系统错误!']);
                }
            }
        }

        $orderItemNum = OrderItem::whereOrderId($thisOrders->id)->count();

        $ordersCommentNum = Comment::whereUserId($user->id)->whereOrderNum($thisOrders->order_num)->count();

        if($orderItemNum == $ordersCommentNum){
            $thisOrders->status = 5;
            $thisOrders->save();
        }

        return response()->json(['level' => 'success','message' => '评论成功','data' => $newComment]);
    }

    /**
     * 获取评论接口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserComment(Request $request){
        $goodsId  = !is_null($request->get('goods_id')) ? $request->get('goods_id') : 0;
        $limit    = !is_null($request->get('limit')) ? $request->get('limit') : 20;
        $page     = !is_null($request->get('page')) ? $request->get('page') : 0;
        $isImg    = !is_null($request->get('is_img')) ? $request->get('is_img') : 0;


        /** @var Goods $thisGoods */
        $thisGoods = Goods::whereId($goodsId)->whereIsShop(1)->first();
        if(!$thisGoods)
            return response()->json(['level' => 'error','message' => '商品已下架！']);

        $commentImg = CommentImg::lists('comment_id');

        /** @var Comment $thisUserComment */
        if($isImg != '' && $isImg != 0){
            $thisUserComments = Comment::whereGoodsId($thisGoods->id)->whereIn('id',$commentImg)->whereIsShow(1)->orderby('created_at','desc')->offset($limit * $page)->limit($limit)->get();
        }else{
            $thisUserComments = Comment::whereGoodsId($thisGoods->id)->whereIsShow(1)->orderby('created_at','desc')->offset($limit * $page)->limit($limit)->get();
        }

        if(count($thisUserComments) > 0){
            foreach($thisUserComments as $thisUserComment){
                /** @var UserInfo $userInfo */
                $userInfo = UserInfo::whereUserId($thisUserComment->user_id)->first();
                if($userInfo){
                    $userInfo->photo_url = FileManager::getImgUrl($userInfo->photo_id);
                }else{
                    $userInfo = (object)[
                        'nickname' => $thisUserComment->nickname,
                        'photo_url' => FileManager::getImgUrl($thisUserComment->photo_id)
                    ];
                }

                $thisUserComment->user_info = $userInfo;

                /** @var CommentImg $thisCommentImg */
                $thisCommentImgs = CommentImg::whereCommentId($thisUserComment->id)->get();
                $commentImageUrls = array();
                if(count($thisCommentImgs) > 0){
                    foreach($thisCommentImgs as $thisCommentImg){
                        $thisCommentImgUrl = FileManager::getImgUrl($thisCommentImg->img_id);
                        array_push($commentImageUrls,$thisCommentImgUrl);
                    }
                }

                $thisUserComment->comment_img = $commentImageUrls;
            }
        }

        $totalCommentNum = Comment::whereGoodsId($thisGoods->id)->whereIsShow(1)->count();

        $imageCommentNum = Comment::whereGoodsId($thisGoods->id)->whereIsShow(1)->whereIn('id',$commentImg)->count();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $thisUserComments,'total_comment_num' => !empty($totalCommentNum) ? $totalCommentNum : 0,'have_img_comment_num' => $imageCommentNum]);
    }

    public function getChongzhiList(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $chongzhiList = Chongzhi::whereStatus(1)->get();

        return response()->json(['level' => 'success','message' => '获取成功','data' => $chongzhiList]);
    }
}
